package me.fenglu.autodeploy;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.compress.compressors.CompressorStreamFactory;

/**
 * Auto deploy project which manage with git version control
 *
 */
public class App {
	private static String gitProjPath = "D:/WORK/workspace/wygz_wx/";
	//private static String gitProjPath = "/home/king/Java/workspace/wygz_wx/";
	public static void main(String[] args) {
		
		List<Map<String, Object>> changeFiles = GitHelper.changedFiles(gitProjPath, "569402ec3bd630f925f5f4f0e07f8221ddbc8c07");
		
		FileClassifier.classify(gitProjPath, changeFiles);
		
		System.err.println(Config.newInstance().getString("test"));
		
		InputStream downstream = null;
		OutputStream upstream = null;
		BufferedOutputStream bos = null;
		Socket client = null;
		try {
			client = new Socket("127.0.0.1", 10240);
			downstream = client.getInputStream();
			upstream = client.getOutputStream();
			upstream.write(changeFiles.size());
			DataInputStream dis = new DataInputStream(downstream);
			String okMsg = dis.readUTF();
System.err.println("server reponse :"+okMsg);
			bos = new BufferedOutputStream(upstream);
			String rootPath = FileClassifier.rootPath;
			List<File> fileList = new ArrayList<File>();
			traverseFile(new File(rootPath), fileList);
			
			byte[] codeTar = FileCompressor.tar(fileList, CompressorStreamFactory.GZIP);

			bos.write(codeTar);
			bos.flush();
			
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(null != client) {
					client.close();
				}
				if(null != bos) {
					bos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private static void traverseFile(File file, List<File> fileList) {
		if(file.isDirectory()) {
			File[] fileArr = file.listFiles();
			for(File f : fileArr) {
				if(f.isDirectory()) {
					traverseFile(f, fileList);
				}else {
					fileList.add(f);
				}
			}
		}
	}
}
